package com.py.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.py.apis.wemedia.IWemediaClient;
import com.py.article.mapper.ApArticleMapper;
import com.py.article.service.HotArticleService;
import com.py.common.constants.ArticleConstants;
import com.py.common.redis.CacheService;
import com.py.model.article.dtos.HotArticleVo;
import com.py.model.article.pojos.ApArticle;
import com.py.model.common.dtos.ResponseResult;
import com.py.model.wemedia.pojos.WmChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author pengy
 * @create 2022-11-23 20:18
 */
@Service
@Slf4j
@Transactional
public class HotarticleServiceImpl implements HotArticleService {
    @Autowired
    private ApArticleMapper apArticleMapper;

    @Autowired
    private IWemediaClient wemediaClient;

    @Autowired
    private CacheService cacheService;

    /**
     * 计算热点文章
     */
    @Override
    public void computeHotArticle() {
        //1获取前五天的文章数据
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DAY_OF_MONTH, -5);
        List<ApArticle> apArticles = apArticleMapper.findArticleListByLast5days(instance.getTime());
        //2计算文章的分值
        List<HotArticleVo> hotArticleList = computeHotArticle(apArticles);
        //3为每个频道缓存30条热点数据
        cacheTagToRedis(hotArticleList);

    }

    /**
     * 给每个频道缓存30条分值较高的文章
     * @param hotArticleList
     */
    private void cacheTagToRedis(List<HotArticleVo> hotArticleList) {
        //查询所有频道
        ResponseResult responseResult = wemediaClient.getChannels();
        if(responseResult.getCode().equals(200)){
            //转换数据
            List<WmChannel> wmChannels = JSON.parseArray(JSON.toJSONString(responseResult.getData()), WmChannel.class);
            for (WmChannel wmChannel : wmChannels) {
                //检索出对应频道的文章列表
                List<HotArticleVo> hotArticleVos = hotArticleList.stream()
                        .filter(hot -> hot.getChannelId().equals(wmChannel.getId()))//过滤，检索出文章对应当前频道的数据
                        .sorted(Comparator.comparing(HotArticleVo::getScore).reversed())//按照分值进行倒序排序
                        .limit(30)//取出30条数据
                        .collect(Collectors.toList());
                //排序，取30条，存入redis
                cacheService.set(ArticleConstants.HOT_ARTICLE_FIRST_PAGE+wmChannel.getId(), JSON.toJSONString(hotArticleVos));

                //给推荐频道设置缓存
                hotArticleList = hotArticleList.stream()
                        .sorted(Comparator.comparing(HotArticleVo::getScore).reversed())
                        .limit(30)
                        .collect(Collectors.toList());
                cacheService.set(ArticleConstants.HOT_ARTICLE_FIRST_PAGE+ArticleConstants.DEFAULT_TAG, JSON.toJSONString(hotArticleList));

            }
        }
    }


    /**
     * 计算文章分值
     *
     * @param apArticles
     * @return
     */
    private List<HotArticleVo> computeHotArticle(List<ApArticle> apArticles) {

        ArrayList<HotArticleVo> hotArticleVos = new ArrayList<>();

        //参数校验
        if (apArticles == null || apArticles.size() == 0) {
            log.info("没有文章数据");
            return null;
        }

        for (ApArticle apArticle : apArticles) {
            //拷贝数据
            HotArticleVo hotArticleVo = new HotArticleVo();
            BeanUtils.copyProperties(apArticles,hotArticleVo);
            //计算文章具体分值
            Integer score = computeScore(apArticle);
            hotArticleVo.setScore(score);
            hotArticleVos.add(hotArticleVo);
        }

        return hotArticleVos;
    }

    /**
     * 计算文章具体分值
     * @param apArticle
     * @return
     */
    private Integer computeScore(ApArticle apArticle) {
        Integer score = 0;

        if(apArticle.getLikes() != null){
            score += apArticle.getLikes()* ArticleConstants.HOT_ARTICLE_LIKE_WEIGHT;
        }

        if(apArticle.getViews() != null){
            score += apArticle.getViews();
        }

        if(apArticle.getComment() != null){
            score += apArticle.getComment()* ArticleConstants.HOT_ARTICLE_COMMENT_WEIGHT;
        }

        if(apArticle.getCollection() != null){
            score += apArticle.getCollection()* ArticleConstants.HOT_ARTICLE_COLLECTION_WEIGHT;
        }

        return score;
    }
}
